package com.nut.lmsc.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    /**
     * 获取spring bean
     * @param name
     * @param cls
     * @param <T>
     * @return
     */
    public synchronized static <T> T getBean(String name, Class<T> cls) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 寻找类本身和他的子类
     * @param c
     * @param <S>
     * @return
     */
    public synchronized static <S> Map<String, S> getBeansOfType(Class<S> c) {
        Map<String, S> beanMaps = applicationContext.getBeansOfType(c);
        return beanMaps;
    }

    /// 获取当前环境
    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    public static Boolean isProd() {
        if ("prod".equals(getActiveProfile())) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
